import { contextBridge, ipcRenderer } from 'electron'
import type { IPCResponse } from '../shared/types'

/**
 * 类型安全的IPC调用包装器
 */
function createIPCInvoker() {
  return {
    // 通用的invoke方法，支持类型安全
    invoke: async <T = any>(channel: string, ...args: any[]): Promise<IPCResponse<T>> => {
      return ipcRenderer.invoke(channel, ...args)
    },

    // 事件监听
    on: (channel: string, callback: (...args: any[]) => void) => {
      ipcRenderer.on(channel, (event, ...args) => callback(...args))
    },

    off: (channel: string, callback: (...args: any[]) => void) => {
      ipcRenderer.off(channel, callback)
    },

    once: (channel: string, callback: (...args: any[]) => void) => {
      ipcRenderer.once(channel, (event, ...args) => callback(...args))
    },

    removeAllListeners: (channel?: string) => {
      if (channel) {
        ipcRenderer.removeAllListeners(channel)
      }
    }
  }
}

// 定义暴露给渲染进程的API
const electronAPI = createIPCInvoker()

// 将API暴露给渲染进程
contextBridge.exposeInMainWorld('electronAPI', electronAPI)

// 类型声明，供渲染进程使用
export type ElectronAPI = typeof electronAPI

// 声明全局类型
declare global {
  interface Window {
    electronAPI: ElectronAPI
  }
}
